<?php

class Wechat{

    /**
     * 微信授权登录获取CODE
     */
    public static function auth($redirect_uri){
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . KEY['wechat']['appid'] . "&redirect_uri=" . urlEncode($redirect_uri) . "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        header("Location: $url");
        exit();
    }

    /**
     * 微信获取access_token
     * 返回用户信息和openid 
     */
    public static function getAuthAccessToken($code){
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . KEY['wechat']['appid'] . "&secret=" . KEY['wechat']['secret'] . "&code=" . $code . "&grant_type=authorization_code";
        $res = json_decode(Http::get($url),true);
        $openid = $res['openid'];
        $access_token = $res['access_token'];
        $userinfo = self::getUserInfo($openid,$access_token);
        return $userinfo;
    }

    /**
     * 获取用户信息
     */
    public static function getUserInfo($openid,$access_token){
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
        $res = json_decode(Http::get($url),true);
        return $res;
    }


    public static function saveAccessToken(){
        
    }

    
}




?>